/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.modules.system.domain.Market;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.MarketRepository;
import me.zhengjie.modules.system.service.MarketService;
import me.zhengjie.modules.system.service.dto.MarketDto;
import me.zhengjie.modules.system.service.dto.MarketQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.MarketMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author azy
* @date 2025-08-31
**/
@Service
@RequiredArgsConstructor
public class MarketServiceImpl implements MarketService {

    private final MarketRepository marketRepository;
    private final MarketMapper marketMapper;

    @Override
    public PageResult<MarketDto> queryAll(MarketQueryCriteria criteria, Pageable pageable){
        if(!SecurityUtils.isAdmin()){
            AssertUtil.notBlank(criteria.getCountyName(),"请输入区县名称");
        }
        Page<Market> page = marketRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(marketMapper::toDto));
    }

    @Override
    public List<MarketDto> queryAll(MarketQueryCriteria criteria){
        if(!SecurityUtils.isAdmin()){
            AssertUtil.notBlank(criteria.getCountyName(),"请输入区县名称");
        }
        return marketMapper.toDto(marketRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public MarketDto findById(Long id) {
        Market market = marketRepository.findById(id).orElseGet(Market::new);
        ValidationUtil.isNull(market.getId(),"Market","id",id);
        return marketMapper.toDto(market);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Market resources) {
        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        marketRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Market resources) {
        Market market = marketRepository.findById(resources.getId()).orElseGet(Market::new);
        ValidationUtil.isNull( market.getId(),"Market","id",resources.getId());
        market.copy(resources);
        market.setUpdateBy(SecurityUtils.getCurrentUsername());
        marketRepository.save(market);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            marketRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<MarketDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MarketDto market : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("信息来源", market.getSourceType());
            map.put("单位名称", market.getName());
            map.put("省", market.getProvinceName());
            map.put("市", market.getCityName());
            map.put("县", market.getCountyName());
            map.put("电话", market.getPhnoe());
            map.put("地址", market.getAddress());
            map.put("创建者", market.getCreateBy());
            map.put("更新者", market.getUpdateBy());
            map.put("创建日期", market.getCreateTime());
            map.put("更新时间", market.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}